import { FolderOpenOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Button,
  Col,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Space,
  Table,
  Tag,
  TimePicker,
  Upload,
} from 'antd';
import axios from 'axios';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { useEffect, useState } from 'react';
import styles from './index.module.css';
import PackingModal from './PackingModal';

const TIME_FORMAT = 'HH:mm:ss';

const normFile = (e) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

dayjs.extend(customParseFormat);

const handlePlannedPickupTime = (time, timeString) => {
  console.log(time, timeString);
};

const handleVehicleRegistrationTime = (time, timeString) => {
  console.log(time, timeString);
};
const handleVehicleCompletionTime = (time, timeString) => {
  console.log(time, timeString);
};

const PROJECT_STATUS_MAP = {
  arrive: '已到达',
  notArrive: '运输中',
  cancellation: '已取消',
};

const COLUMNS = [
  {
    title: '运单号',
    dataIndex: 'billNumber',
    key: 'billNumber',
  },
  {
    title: '项目状态',
    dataIndex: 'projectStatus',
    key: 'projectStatus',
    render: (_, { projectStatus }) => {
      let color = '';
      switch (projectStatus) {
        case 'arrive':
          color = 'geekblue';
          break;
        case 'notArrive':
          color = 'volcano';
          break;
        case 'cancellation':
          color = 'red';
          break;
        default:
          color = 'geekblue';
          break;
      }
      return (
        <Tag color={color} key={projectStatus}>
          {PROJECT_STATUS_MAP[projectStatus]}
        </Tag>
      );
    },
  },
  {
    title: '计划提货时间',
    dataIndex: 'plannedPickupTime',
    key: 'plannedPickupTime',
  },
  {
    title: '车辆登记到位时间',
    dataIndex: 'vehicleRegistrationTime',
    key: 'vehicleRegistrationTime',
  },
  {
    title: '车辆装完时间',
    dataIndex: 'vehicleCompletionTime',
    key: 'vehicleCompletionTime',
  },
  {
    title: '车牌号',
    dataIndex: 'licenseNumber',
    key: 'licenseNumber',
  },
  {
    title: '司机姓名',
    dataIndex: 'driverNumber',
    key: 'driverNumber',
  },
  {
    title: '单证',
    dataIndex: 'documents',
    key: 'documents',
    align: 'center',
    render: () => <FolderOpenOutlined />,
  },
  // {
  //   title: '运踪',
  //   dataIndex: 'trajectories',
  //   key: 'trajectories',
  // },
];

const TransportPlan = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [form3] = Form.useForm();

  const [dataSource, setDataSource] = useState([]);

  const loadData = () => {
    // 发起网络请求获取后端数据
    axios
      .get('http://localhost:9090/dispatch/page', { params: { billNumber: null } })
      .then((response) => {
        // 请求成功时更新dataSource的状态
        setDataSource(response.data.data.list);
      })
      .catch((error) => {
        // 处理请求失败的情况
        console.error(error);
      });
  };
  useEffect(() => {
    loadData();
  }, []);

  // const router=userRouter  进行跳转
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    showSizeChanger: true,
    total: 25,
  });
  const handleSearchFinish = () => {
    form1.validateFields().then((values) => {
      axios
        .get('http://localhost:9090/dispatch/page', { params: values })
        .then((response) => {
          // 请求成功时更新dataSource的状态
          setDataSource(response.data.data.list);
        })
        .catch((error) => {
          // 处理请求失败的情况
          console.error(error);
        });
    });
    // 搜索函数
    // 需要请求数据库数据与values进行对比，相同展示到表单中
    console.log(values);
  };
  const handleSearchReset = () => {
    // 重置函数
    loadData();
    console.log(form1);
    form1.resetFields();
  };
  const handleTransportPlanEdit = (row) => {
    // 弹窗来进行修改数据
    // 先获取当前数据，将当前数据加载到弹窗里面
  };
  const handleTransportPlandelete = (row) => {
    // 需要接口，删除数据
    axios
      .delete('http://localhost:9090/dispatch/delete/' + row.id)
      .then((response) => {
        loadData();
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
      })
      .catch((error) => {
        console.error(error);
      });
  };
  const handleTableChange = (pagination) => {
    // 表格分页跳转
    console.log(pagination);
    setPagination(pagination);
  };

  const [visiableAdd, setVisiableAdd] = useState(false);
  const [visiableEdit, setVisiableEdit] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const handleAdd = () => {
    // 假设现在已经取到数值了
    form2
      .validateFields()
      .then((values) => {
        let { plannedPickupTime, vehicleCompletionTime, vehicleRegistrationTime } = values;
        const params = {
          ...values,
          plannedPickupTime: plannedPickupTime.format(TIME_FORMAT),
          vehicleCompletionTime: vehicleCompletionTime.format(TIME_FORMAT),
          vehicleRegistrationTime: vehicleRegistrationTime.format(TIME_FORMAT),
        };
        axios.post('http://localhost:9090/dispatch/save/', params).then((response) => {
          messageApi.open({
            type: 'success',
            content: '添加成功',
          });
          loadData();
        });
        form2.resetFields();
        closeModalAdd();
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };

  const onModalOpen = (row) => {
    // const { billNumber,
    //   documents,
    //   driverNumber,
    //   licenseNumber,
    //   plannedPickupTime,
    //   projectStatus,
    //   trajectories,
    //   vehicleCompletionTime,
    //   vehicleRegistrationTime } = row;
    console.log('currentRow', row);
    form3.setFieldsValue({
      ...row,
      plannedPickupTime: dayjs(row.plannedPickupTime, TIME_FORMAT),
      vehicleCompletionTime: dayjs(row.vehicleCompletionTime, TIME_FORMAT),
      vehicleRegistrationTime: dayjs(row.vehicleRegistrationTime, TIME_FORMAT),
      documents: [],
    });
    setVisiableEdit(true);
  };

  const handleEdit = () => {
    form3
      .validateFields()
      .then((values) => {
        let { plannedPickupTime, vehicleCompletionTime, vehicleRegistrationTime } = values;
        const params = {
          ...values,
          plannedPickupTime: plannedPickupTime.format(TIME_FORMAT),
          vehicleCompletionTime: vehicleCompletionTime.format(TIME_FORMAT),
          vehicleRegistrationTime: vehicleRegistrationTime.format(TIME_FORMAT),
        };
        axios.put('http://localhost:9090/dispatch/update/', params).then((response) => {
          messageApi.open({
            type: 'success',
            content: '修改成功',
          });
          loadData();
        });
        form3.resetFields();
        closeModalEdit();
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  };

  const columns = [
    ...COLUMNS,
    {
      title: '操作',
      key: 'action',
      render: (_, row) => {
        return (
          <Space size="middle">
            <a onClick={showModal}>装运详情</a>
            <a onClick={() => onModalOpen(row)}>编辑</a>
            <a onClick={() => showModalDelete(row)} style={{ color: '#ff4d4f' }}>
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const [VisibleDelete, setVisibleDelete] = useState(false);
  const [selectedRow, setSelectedRow] = useState(null); // 用于存储要删除的行数据

  const showModalDelete = (row) => {
    setSelectedRow(row);
    setVisibleDelete(true);
  };

  const handleDelete = () => {
    if (selectedRow) {
      // 调用删除函数
      handleTransportPlandelete(selectedRow);
      setVisibleDelete(false);
    }
  };

  const closeModalDelete = () => {
    setVisibleDelete(false);
  };

  const closeModalAdd = () => {
    setVisiableAdd(false);
  };

  const closeModalEdit = () => {
    setVisiableEdit(false);
  };

  // -------------装箱弹窗方法---------------------
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <PageContainer>
      {contextHolder}
      <Form
        name="search"
        form={form1}
        onFinish={handleSearchFinish}
        initialValues={{
          billNumber: '',
        }}
      >
        <Row gutter={24}>
          <Col
            span={16}
            style={{
              display: 'flex',
            }}
          >
            <Form.Item name="billNumber" label="运单号">
              <Input placeholder="请输入运单号" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Button type="primary" htmlType="submit" style={{ margin: ' 0 8px' }}>
              搜索
            </Button>
            <Button htmlType="submit" onClick={handleSearchReset}>
              清空
            </Button>
          </Col>
          <Col
            span={8}
            style={{
              display: 'flex',
              justifyContent: 'flex-end',
            }}
          >
            <Button type="primary" onClick={() => setVisiableAdd(true)}>
              添加
            </Button>
          </Col>
        </Row>
      </Form>

      <Modal
        title="添加"
        open={visiableAdd}
        onOk={handleAdd}
        onCancel={closeModalAdd}
        afterClose={closeModalAdd}
        // onFinish={handleAdd}
      >
        <p>
          <Form
            form={form2}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            layout="horizontal"
            style={{ maxWidth: 600 }}
          >
            <Form.Item name="billNumber" label="运单号" rules={[{ required: true }]}>
              <Input placeholder="请输入运单号" />
            </Form.Item>
            <Form.Item name="projectStatus" label="项目状态">
              <Radio.Group>
                <Radio value="arrive"> 已到达 </Radio>
                <Radio value="notArrive"> 未到达 </Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item name="plannedPickupTime" label="计划提货时间">
              <TimePicker
                onChange={handlePlannedPickupTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="vehicleRegistrationTime" label="车辆登记到位时间">
              <TimePicker
                onChange={handleVehicleRegistrationTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="vehicleCompletionTime" label="车辆装完时间">
              <TimePicker
                onChange={handleVehicleCompletionTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="licenseNumber" label="车牌号">
              <Input placeholder="请输入车牌号" />
            </Form.Item>

            <Form.Item name="driverNumber" label="司机姓名">
              <Input placeholder="请输入司机姓名" />
            </Form.Item>

            <Form.Item
              name="documents"
              label="单证"
              valuePropName="fileList"
              getValueFromEvent={normFile}
            >
              <Upload action="/upload.do" listType="picture-card">
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              </Upload>
            </Form.Item>

            {/* <Form.Item name="trajectories" label="运踪">
              <Input placeholder="请输入车牌号" />
            </Form.Item> */}
          </Form>
        </p>
      </Modal>

      <Modal
        title="修改"
        open={visiableEdit}
        onOk={handleEdit}
        onCancel={closeModalEdit}
        afterClose={closeModalEdit}
        // onFinish={handleAdd}
      >
        <p>
          <Form
            form={form3}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            layout="horizontal"
            style={{ maxWidth: 600 }}
          >
            <Form.Item
              name="id"
              label="ID"
              rules={[{ required: false }]}
              style={{ display: 'none' }}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item name="billNumber" label="运单号" rules={[{ required: true }]}>
              <Input placeholder="请输入运单号" />
            </Form.Item>
            <Form.Item name="projectStatus" label="项目状态">
              <Radio.Group>
                <Radio value="arrive"> 已到达 </Radio>
                <Radio value="notArrive"> 运输中 </Radio>
                <Radio value="cancellation"> 已取消 </Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item name="plannedPickupTime" label="计划提货时间">
              <TimePicker
                onChange={handlePlannedPickupTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="vehicleRegistrationTime" label="车辆登记到位时间">
              <TimePicker
                onChange={handleVehicleRegistrationTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="vehicleCompletionTime" label="车辆装完时间">
              <TimePicker
                onChange={handleVehicleCompletionTime}
                defaultValue={dayjs('00:00:00', TIME_FORMAT)}
              />
            </Form.Item>

            <Form.Item name="licenseNumber" label="车牌号">
              <Input placeholder="请输入车牌号" />
            </Form.Item>

            <Form.Item name="driverNumber" label="司机号">
              <Input placeholder="请输入司机号" />
            </Form.Item>

            <Form.Item
              name="documents"
              label="单证"
              valuePropName="fileList"
              getValueFromEvent={normFile}
            >
              <Upload action="/upload.do" listType="picture-card">
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              </Upload>
            </Form.Item>

            {/* <Form.Item name="trajectories" label="运踪">
              <Input placeholder="请输入车运踪" />
            </Form.Item> */}
          </Form>
        </p>
      </Modal>

      <Modal
        title="确认删除"
        visible={VisibleDelete}
        onOk={handleDelete}
        onCancel={closeModalDelete}
      >
        <p>确定要删除吗？</p>
      </Modal>
      {/* 货车装箱详情弹窗 */}
      <PackingModal {...{ isModalOpen, handleOk, handleCancel }} />

      <div className={styles.tableWrap}>
        <Table
          dataSource={dataSource}
          columns={columns}
          rowKey={'id'}
          scroll={{ x: 1000 }}
          onChange={handleTableChange}
          pagination={{ ...pagination, showTotal: () => `共${pagination.total}条` }}
        />
      </div>
    </PageContainer>
  );
};

export default TransportPlan;
